package com.credit.mola.app.utils.event.track

import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.HttpHelper
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.log.HHLog
import org.json.JSONArray
import org.json.JSONObject

/**
 * 埋点上报接口
 */
interface TrackEventUploader {
    suspend fun upload(events: List<TrackEvent>)
}

class CreditMolaTrackEventUploader : TrackEventUploader {
    override suspend fun upload(events: List<TrackEvent>) {
        // 模拟网络请求上传事件
        HHLog.d("TrackUploader Uploading ${events.size} events")
        //上报
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.TRACK_EVENT_BATCH)
        }
        val array = JSONArray()
        for (point in events) {
            HHLog.e("track event >>> id=" + point.id + ">>>type=" + point.eventType + ">>>remark=" + point.remark + ">>>timestamp=" + point.eventTime + ">>>isReported=" + point.uploaded)
            val obj = JSONObject()
            obj.put("id", point.id)
            obj.put("type", point.eventType)
            obj.put("remark", point.remark)
            obj.put("timestamp", point.eventTime)
            array.put(obj)
        }
        params.put("list", array)
        val upUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        HttpHelper.post(upUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }
}